<template>
  <MesBox
    v-model="reworkVisible"
    title="生成返工工单"
    :width="1000"
    :height="300"
  >
    <MesForm
      ref="reworkForm"
      :formFields="formFields"
      :formRules="formRules"
    ></MesForm>
    <template #footer>
      <el-button type="danger" @click="createReworkOrder">
        <i class="el-icon-check"></i>
        保存
      </el-button>
    </template>
  </MesBox>
</template>

<script setup>
import MesBox from '@/components/basic/MesBox'
import MesForm from '@/components/basic/MesForm'
import { getNowDate } from '@/uitils/dateFormatUtil'
import { getCurrentInstance, ref } from 'vue'

const emit = defineEmits(['parentCall'])
const that = getCurrentInstance().appContext.config.globalProperties
const reworkForm = ref(null)
let reworkVisible = ref(false)
let formFields = ref({
  moCode: '',
  process_Id: null,
  qty: 0,
  startTime: getNowDate(),
  endTime: '',
  productName: '',
  productCode: '',
  productStandard: '',
})
const formRules = [
  [
    {
      title: '订单号',
      field: 'moCode',
      readonly: true,
    },
    {
      title: '产品名称',
      field: 'productName',
      readonly: true,
    },
  ],
  [
    {
      title: '产品编码',
      field: 'productCode',
      readonly: true,
    },
    {
      title: '产品规格',
      field: 'productStandard',
      readonly: true,
    },
  ],
  [
    {
      title: '工艺路线',
      field: 'process_Id',
      required: true,
      type: 'select',
      dataKey: 'reworkProcessList',
    },
    {
      title: '数量',
      field: 'qty',
      required: true,
      type: 'number',
      min: 0,
    },
  ],
  [
    {
      title: '计划开始时间',
      field: 'startTime',
      required: true,
      type: 'datetime',
    },
    {
      title: '计划结束时间',
      field: 'endTime',
      required: true,
      type: 'datetime',
    },
  ],
]

//生成返工工单
const createReworkOrder = () => {
  reworkForm.value.validate(async (valid) => {
    if (valid) {
      const res = await that.http.post(
        '/api/Production_WorkOrder/CreateReWorkOrder',
        formFields.value,
        true
      )

      if (res.status) {
        that.$message.success('创建成功')
        reworkVisible.value = false
        emit('parentCall', ($parent) => {
          $parent.search()
        })
        formFields.value = {
          moCode: '',
          process_Id: null,
          qty: 0,
          startTime: getNowDate(),
          endTime: '',
          productName: '',
          productCode: '',
          productStandard: '',
        }
      } else {
        that.$message.error(res.message)
      }
    }
  })
}

const open = (row) => {
  reworkVisible.value = true
  for (const key in formFields.value) {
    formFields.value[key] = row[key]
  }
}

defineExpose({
  open,
})
</script>
